<?php
/**
 * 更新专辑评论
 * 
 * @author yangchao
 * @since 2012-03-19
 */


if (!file_exists("../../SINASRV_CONFIG")) {
	echo "Read the sinasrv config error!\n";
//	exit();
} else {
   $array_config = parse_ini_file("../../SINASRV_CONFIG", true); $_SERVER = array_merge($_SERVER, $array_config); 
}
define("CRON_NAME","cron_get_comment_by_food_status_mid");//cro名称，要求唯一
set_time_limit(0);
$_GET["db_debug"] = true;
$_GET["no_pref_debug"] = true;

//评论15分钟执行一次，每次1W mid更新 开始mid为7天内的mid
define("PCOUNT",100);//每次处理多少mid
define("MAX_PAGE",100); //定义每个进程处理最大的页数
define("TOTAL_PROCESS",1);//添加新进程需要更新这个配置
define("CRON_TYPE","status_comment");//cron的类型
define("NOW_PROCESS",$argv[1] ? $argv[1] : 0);//当前进程ID=0 可以申请如下php xxx 1
define("CRON_START_TIME",time());

include_once($_SERVER["DOCUMENT_ROOT"]. "/core/inc.php");
include_once($_SERVER["DOCUMENT_ROOT"]. "/include/mblogv2/mod_get_mblogv2_from_api.php");
include_once($_SERVER["DOCUMENT_ROOT"]. "/include/foodv2/inc.php");



$g_cgival = array();
$g_show = array();
$g_pro = array();



class mod_cron_engine_main extends mod_cron_engine
{
	function __construct($current_process_id)
	{
		parent::__construct($current_process_id,CRON_NAME);
	}
	
	
	function craw()
	{
		$this->get_data();
	}
	
	
	function  run()
	{
		//开始跑cron之前预先获取数据（start_id等）
		$this->before_run();
		
		//正式获取数据
		$this->craw();
		
		
		$this->after_run();
	}
	
	function ini_start_id()
	{
		$db_food_status = new db_food_status();
		$res = $db_food_status->cron_get_status_id_by_time();
		$start_id = $res["status_id"] ? $res["status_id"] : 0 ;
		
		$db_cron_start_id = new db_cron_start_id();
		$res = $this->replace_into_data($this->current_process_id,$start_id);	
		
		return $start_id;
	}
		
	function get_data()
	{
		$db_food_tag = new db_food_tag();
		$mblog_from_api = new mblog_from_api();
		$db_food_status = new db_food_status();
		
		//获取status的总数
		$count = $db_food_status->cron_get_food_status_count($this->start_id);
		
		if($count == 0)
		{
			//如果获取不到需要更新的数据，初始化cron_start_id
			$start_id = $this->ini_start_id();
			
			$this->start_id = $start_id ;
			$count = $db_food_status->cron_get_food_status_count($this->start_id);
		}
		
		
		echo "process:".NOW_PROCESS.":album_mid_count:$count<br>\n";
		$total_page = ceil($count/PCOUNT);
		
		if($total_page > MAX_PAGE && defined("MAX_PAGE")) $total_page = MAX_PAGE;
		
		//根据mid做分页
		for($i=1;$i<=$total_page;$i++)
		{
			$this->get_list_by_page($i);
		}
		
		
	}
		
	
	function get_list_by_page($p)
	{
		
		//执行时间超过15分钟，退出
		if(time() - CRON_START_TIME > 900)
		{
			exit;
		}
		
		$db_food_album = new db_food_album();
		$mblog_from_api = new mblog_from_api();
		$db_food_status = new db_food_status();
		$db_food_status_comment = new db_food_status_comment();
		$db_food_message_at = new db_food_message_at();
        $db_food_user = new db_food_user();
        
		//分批次取mid
		$status_list = $db_food_status->cron_get_food_status_list($this->start_id,$p,PCOUNT);
		
		//构造sql,一次性插入
		$sql_status_comment = " insert into food_status_comment (site_id,status_id,content,comment_mid,create_uid,create_nickname,create_ip,create_time,status,source) values ";
		$sql_status_comment_array = array();
		
		$sql_comment_idx = "insert into food_comment_idx (message_class,message_id,message_uid,message_content,comment_id,comment_uid,comment_content,comment_to_id,comment_to_uid,comment_to_content,create_uid,create_nickname,create_ip,create_time,status,source) values";
		$sql_comment_idx_array = array();
		
		$sql_message_at = "insert into food_message_at (uid, nickname, class, message_id, message_uid, message_content, comment_id, comment_uid, comment_content, comment_to_id, comment_to_uid, comment_to_content, create_uid, create_nickname,source,create_time,status) values ";
		$sql_message_at_array = array();
		
		$update_start_id = 0;
		
		foreach($status_list as $key => $value)
		{
			$mid = $value["mid"];
			$status_id  = $value["status_id"];
			$site_id  = $value["site_id"];
			
			if($mid && $status_id )
			{
				if($status_id % TOTAL_PROCESS != NOW_PROCESS)//用总进程做控制 example: 3个进程  php xxx 1 只会执行除3余1的id
				{
					continue;
				}
				
				$comment_info = $db_food_status_comment->cron_get_max_mid_by_status_id($status_id);
				$since_id = $comment_info["mid"];
				
				//根据话题抓取
				$mblog_list = $mblog_from_api->api_get_comment_by_mid($mid,$p=1,$pcount=50,0,$since_id);
				
				echo "{$mid}:count:{$mblog_list["data"]["count"]}|get_count".count($mblog_list["data"]["result"])."<br>\n";
				
				if($mblog_list["data"]["result"])
				{
					foreach($mblog_list["data"]["result"] as $value1)
					{
						//如果时间跟最大时间相同，跳过
						if($value1["id"] == $since_id)
						{
							continue;
						}
					
						$create_time = date("Y-m-d H:i:s",strtotime($value1["created_at"]));
						$text = mysql_escape_string(str_replace("'","",$value1["text"]));
						
						if($value1["reply_comment"])
						{
							//获取评论回复信息
							$comment_to_uid = $value1["reply_comment"]["user"]["id"];
							$comment_to_content = mysql_escape_string(str_replace("'","",$value1["reply_comment"]["text"])); 
							$comment_mid = $value1["reply_comment"]["id"];
							
							$comment_info = $db_food_status_comment->cron_get_id_by_mid($comment_mid);
							$comment_to_id = $comment_info["id"];
							
						}
						else
						{
							$comment_to_id= 0;
							$comment_to_uid= 0;
							$comment_to_content="";
							
						}
						$sql = $sql_status_comment . "({$site_id},{$status_id}, '".$text."' , {$value1["idstr"]},  {$value1["user"]["id"]} , '".mysql_escape_string($value1["user"]["screen_name"])."',0,'{$create_time}',1,'{$value1["source"]}')";
						$db_food_status->query($sql);
						$comment_id = $db_food_status->get_lastinsertid();
						$comment_uid = $value1["user"]["id"];
						
						$value1["status"]["text"] = mysql_escape_string(str_replace("'","",$value1["status"]["text"]));
						
						$comment_content = mysql_escape_string(str_replace("'","",$value1["text"]));
					
						$sql_comment_idx_array[] = "( 1,'{$status_id}','{$value1["status"]["user"]["id"]}','{$value1["status"]["text"]}',{$comment_id},'{$comment_uid}','{$comment_content}','{$comment_to_id}', '{$comment_to_uid}','{$comment_to_content}','{$value1["user"]["id"]}','{$value1["user"]["screen_name"]}',
						  0,'{$create_time}',1 ,'{$value1["source"]}')";
						
						
						$at_users = mod_status_core::get_nickname($comment_content,array($value1["status"]["user"]["screen_name"]));
						if($at_users)
						{
							foreach ($at_users as $nickname) {
					            // 获取用户信息
					            $user_info = $db_food_user->get_food_user_by_nickname($nickname);
					             if(!empty($user_info))
					            {
					                $sql_message_at_array[] = "('{$user_info['uid']}', '{$user_info['nickname']}', 1 , $status_id, '{$value1["status"]["user"]["id"]}', '{$value1["status"]["text"]}', $comment_id, $comment_uid, '{$comment_content}', $comment_to_id, $comment_to_uid, '{$comment_to_content}', '{$value1["user"]["id"]}', '{$value1["user"]["screen_name"]}','{$value1["source"]}','{$create_time}',1)";					           
					             }
					        }
						}
						
					}
					
					//更新评论数
					$comment_count = $db_food_status_comment->cron_get_count_by_status_id($status_id);
					
					$db_food_status->cron_update_food_status_by_status_id($status_id,"","","",$comment_count);
					
			
				}
				//记录cron更新到哪
				$update_start_id = $status_id;
			
			}
			
		}
		if($sql_comment_idx_array)
		{
			$sql_comment_idx  = $sql_comment_idx. join(",",$sql_comment_idx_array);
			$db_food_status->query($sql_comment_idx);
			
			
		}
		
		if($sql_message_at_array)
		{
			$sql_message_at  = $sql_message_at. join(",",$sql_message_at_array);
			$db_food_status->query($sql_message_at);
			
		}
		
		if($update_start_id)//更新抓取的start_id到数据库
		{
			$res = $this->replace_into_data($update_start_id);	
		}
		
	}

}



$m = new mod_cron_engine_main(NOW_PROCESS);
$m->run();